import {Injectable} from '@angular/core';
import {ConsulRepository} from '../repo/consul.repo';
import {map, tap} from 'rxjs/operators';
import {JsonConvert} from 'json2typescript';
import {ServiceEntity} from '../model/service-entity';
import {Observable} from 'rxjs';
import {ConfigService} from './config.service';

@Injectable({
  providedIn: 'root'
})
export class ConsulService {
  private json = new JsonConvert();

  constructor(private config: ConfigService, private repo: ConsulRepository) {
  }

  getService(): Observable<ServiceEntity[]> {
    const obs = this.repo.getService(this.config);
    return obs.pipe(map(v => {
      return this.json.deserializeArray(Object.values(v), ServiceEntity);
    }));
  }

  deregister(serviceId: string): Observable<boolean> {
    const obs = this.repo.deregister(serviceId, this.config);
    return obs.pipe(tap(x => {
      // console.log(x);
    }));
  }

  healthCheck(address: string): Observable<any> {
    const obs = this.repo.healthCheck(address);
    return obs.pipe(
      tap(x => {
        // console.log(x);
      }),
      map(v => v.status));
  }
}
